<script setup lang="ts">
import { ref, onMounted, reactive, watch } from "vue";
import { ElMessage, ElForm, ElFormItem, ElInput, ElSelect, ElOption, ElButton, ElMessageBox } from "element-plus";
import { useRoute } from "vue-router";
import { getDeptGroupConfigsApi, setDeptGroupConfigsApi } from '@/api/configs/deptConfig';

const configGroupName = "base";

const props = defineProps<{
  deptId: number;
}>();

// 定义基础配置类型
interface BaseConfigModel {
  contactAddress: string; // 联系地址
  personInCharge: string; // 负责人
  contactPhone: string; // 联系电话
  language: string; // 使用语言
}

const route = useRoute();
const formRef = ref<InstanceType<typeof ElForm>>();

// 初始化表单数据
const formData = reactive<{
  deptId: number;
  groupName: string;
  config: BaseConfigModel;
  updatedAt: string;
}>({
  deptId: 0,
  groupName: configGroupName,
  config: {
    contactAddress: '',
    personInCharge: '',
    contactPhone: '',
    language: 'cn',
  },
  updatedAt: ''
});

// 语言选项
const languageOptions = [
  { label: '中文', value: 'cn' },
  { label: '英语', value: 'en' }
];

watch(() => props.deptId, (newVal:number) => {
  if (newVal) {
    resetForm()
    formData.deptId = newVal;
    loadConfigData();
  }
},{
  deep: true
});

const loadConfigData = () => {
  const deptId = formData.deptId;
  // 获取部门基础配置
  getDeptGroupConfigsApi({
    deptId: deptId,
    groupName: formData.groupName
  }).then(res => {
    if (res.code === 0 && res.data?.configs) {
      formData.updatedAt = res.data.updatedAt || '';
      try {
        // 解析配置数据
        const configMap: Record<string, any> = {};
        res.data.configs.forEach(item => {
          configMap[item.configKey] = item.configValue;
        });

        // 填充表单数据
        formData.config = {
          contactAddress: configMap.contactAddress || '',
          personInCharge: configMap.personInCharge || '',
          contactPhone: configMap.contactPhone || '',
          language: configMap.language || 'cn',
        };
      } catch (e) {
        console.error('解析配置数据失败', e);
      }
    }
  });
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return;
  try {
    await formRef.value.validate();
    const submitData = {
      deptId: formData.deptId,
      groupName: formData.groupName,
      configs: [
        { configKey: 'contactAddress', configValue: formData.config.contactAddress, configDesc: '联系地址' },
        { configKey: 'personInCharge', configValue: formData.config.personInCharge, configDesc: '负责人' },
        { configKey: 'contactPhone', configValue: formData.config.contactPhone, configDesc: '联系电话' },
        { configKey: 'language', configValue: formData.config.language, configDesc: '使用语言' }
      ]
    };

    ElMessageBox.confirm(
      '确定要保存当前部门基础配置吗？',
      '确认提交',
      { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }
    ).then(async () => {
      await setDeptGroupConfigsApi(submitData);
      ElMessage.success('保存成功');
    }).catch(() => ElMessage.info('已取消保存'));
  } catch (error) {
    ElMessage.error('表单验证失败，请检查填写内容');
  }
};

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields();
};
</script>

<template>
  <el-form ref="formRef" :model="formData" label-width="160px" class="form-container">
    <el-form-item label="部门ID" prop="deptId" v-if="formData.deptId">
      <el-input v-model="formData.deptId" disabled />
    </el-form-item>
    <el-form-item label="配置组名" prop="groupName">
      <el-input v-model="formData.groupName" disabled />
    </el-form-item>

    <el-form-item
      label="联系地址"
      prop="config.contactAddress"
      :rules="[{ required: true, message: '请输入联系地址', trigger: 'blur' }]"
    >
      <el-input v-model="formData.config.contactAddress" placeholder="请输入联系地址" />
    </el-form-item>

    <el-form-item
      label="负责人"
      prop="config.personInCharge"
      :rules="[{ required: true, message: '请输入负责人', trigger: 'blur' }]"
    >
      <el-input v-model="formData.config.personInCharge" placeholder="请输入负责人" />
    </el-form-item>

    <el-form-item
      label="联系电话"
      prop="config.contactPhone"
      :rules="[
        { required: true, message: '请输入联系电话', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
      ]"
    >
      <el-input v-model="formData.config.contactPhone" placeholder="请输入联系电话" />
    </el-form-item>

    <el-form-item
      label="使用语言"
      prop="config.language"
      :rules="[{ required: true, message: '请选择使用语言', trigger: 'change' }]"
    >
      <el-select v-model="formData.config.language" placeholder="请选择使用语言">
        <el-option v-for="option in languageOptions" :key="option.value" :label="option.label" :value="option.value" />
      </el-select>
    </el-form-item>

    <!-- 更新时间显示 -->
    <el-form-item label="更新时间" v-if="formData.updatedAt">
      <el-input v-model="formData.updatedAt" disabled placeholder="暂无更新时间" />
    </el-form-item>

    <el-form-item class="form-actions">
      <el-button type="primary" @click="submitForm">提交</el-button>
      <el-button @click="resetForm">重置</el-button>
    </el-form-item>
  </el-form>
</template>

<style scoped lang="scss">
.form-container { max-width: 800px; margin: 20px auto; padding: 20px; }
.form-actions { display: flex; justify-content: center; gap: 10px; margin-top: 30px; }
</style>
